package com.sky.service.user.impl;

import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.exception.BaseException;
import com.sky.mapper.user.UserAddressBookMapper;
import com.sky.pojo.AddressBook;
import com.sky.service.user.UserAddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author ljk74
 */
@Service
@Slf4j
public class UserAddressBookServiceImpl implements UserAddressBookService {
    @Autowired
    private UserAddressBookMapper userAddressBookMapper;

    @Override
    public void addAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(StatusConstant.DISABLE);
        userAddressBookMapper.addAddressBook(addressBook);
    }

    @Override
    public List<AddressBook> findList() {
        return userAddressBookMapper.findAll(BaseContext.getCurrentId());
    }

    @Override
    public AddressBook findDefault() {
        List<AddressBook> list = userAddressBookMapper.findDefault(StatusConstant.ENABLE,BaseContext.getCurrentId());
        if (CollectionUtils.isEmpty(list)){
            throw new BaseException(MessageConstant.DEFAULT_ADDRESS_BOOK_NOT_FOUND);
        }
        return list.get(0);
    }

    @Override
    public void updateAddressBook(AddressBook addressBook) {
        userAddressBookMapper.updateAddressBook(addressBook);
    }

    @Override
    public AddressBook findById(Long id) {
        return userAddressBookMapper.findById(id);
    }

    @Override
    public void delById(Long id) {
        userAddressBookMapper.delById(id);
    }

    @Override
    @Transactional
    public void setDefault(AddressBook addressBook) {
        //更新所有is_default为0
        userAddressBookMapper.updateIsDefault(BaseContext.getCurrentId());
        addressBook.setIsDefault(StatusConstant.ENABLE);
        userAddressBookMapper.updateAddressBook(addressBook);
    }
}
